#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
using namespace std;
#define NUM 1024

extern char** environ;

int main()
{
  // 属于是死循环
  while (1)
  {
    // 首先是打印地址
    cout << "[afeng@_myshell]$ ";
    fflush(stdout); // 解决缓冲区的问题

    // 然后开始接收指令
    char instruct[NUM];
    memset(instruct, '\0', sizeof instruct);
    if (fgets(instruct, sizeof instruct, stdin) == NULL)
    {
      continue;
    }
    instruct[strlen(instruct) - 1] = '\0';

    // 开始拆分出指令
    char* argv[100] = {0};
    argv[0] = strtok(instruct," ");
    int i = 1;
    while (argv[i++] = strtok(NULL, " "));
    //for (int n = 0;argv[n]; n++)
    //  cout << argv[n] << endl;
    
    // 内置命令 1.我们通过子进程替换打印我们需要的结果，父进程不受影响
    // 当需要更改路径时，目标是父进程
    if (strcmp(argv[0],"cd") == 0)
    {
        if (argv[1] != NULL)
          chdir(argv[1]);
        continue;
    }

    if (strcmp(argv[0], "export") == 0)
    { // 通过putenv增加环境变量
      int ret = 1;
      if (argv[1])
        ret = putenv(argv[1]);
        //if (ret == 0) cout << "put success" << endl;
        ////for (int i = 0; environ[i]; i++)
        //  cout << environ[i] << endl;
        continue;
    }

    pid_t pd = fork();
    if (pd == 0) // child
    {
      execvp(argv[0], argv);
      exit(-1);
    }
    else{
      // parent
      int status;
      pid_t ret = waitpid(pd, &status, 0);
      if (ret > 0 )
      {
        cout << "子进程运行成功，退出码:" << WEXITSTATUS(status)<< endl;
      }else{
        cout << "子进程运行失败,退出码:" << WEXITSTATUS(status)<< endl;
      }
    }
  }
  return 0;
}
